/**
 * Created by sxx on 2017/5/3.
 */
import "./index.less";
import {projSts} from "../config.js";

import bidListTpl from "./bid_list.handlebars";
import paginationTpl from "./paging.handlebars";

let token = sessionStorage.getItem('supplier_token');
// console.log(bidListTpl);
// var data = {
//     testItem: 'testItem'
// };
// var test = bidListTpl(data);
// console.log(test);
// jQuery('.testHandlebars').html(test);

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

var PublicBiddingList = {
    pageNo: 1,
    pageSize: 20,
    maxPage: 1,
    isFirstPage: false,
    isLastPage: false,
    total: 0,
    init: function(){
        this.getBiddingData()
            .then(this.renderBidList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    },
    getBiddingData: function() {
        return new Promise((resolve, reject)=>{
            let self = this;
            let data ={
                "bidRngTyp":"1"
            };
            $.ajax({
                url: HOST_ADDR + `/cpmp/bidProjOnMngForSplr/queryProjs/${self.pageNo}/${self.pageSize}`,
                type: 'post',
                dataType: 'json',
                headers: {
                    'access_token': token,
                    'login_type': 'splr',
                    'IsMCompany':ISMCOMPANY
                },
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function (resp) {
                    if (resp.success) {
                        console.log(resp);
                        resolve(resp);
                    }
                    else {
                        console.log(resp.msgInf);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });


        });

    },
    // 渲染列表

    renderBidList: function(resp){
        let self = PublicBiddingList;
        // 处理数据begin
        self.total = resp.data.count;
        self.isFirstPage = self.pageNo===1;
        self.maxPage = Math.ceil(self.total/self.pageSize);
        console.log(resp.data.list);
        $.each(resp.data.list,function(index,item){
            item.applyAvailabel = item.projSts === "20";
            item.projSts = projSts[item.projSts]||'暂无状态';
            if (item.bidEndTim != null&&item.bidEndTim !='') {
                item.bidEndTimeFormat = (new Date(item.bidEndTim)).Format("yyyy-MM-dd hh:mm:ss");
            } else {
                item.bidEndTimeFormat = '';
            }
        });
        // 处理数据end
        if(self.pageNo * self.pageSize >= self.total){
            self.isLastPage = true;
        }else{
            self.isLastPage = false;
        }

        let resultHtml = bidListTpl({bidList: resp.data.list});
        $('.J_bid-list').html(resultHtml);
    },

    // 渲染分页
    renderPagination: function(){
        let self = PublicBiddingList;
        let pageList = [];
        for(let i=0; i<self.maxPage; i++){
            pageList.push({idx: i+1});
        }
        console.log(self.total);
        let paginationHtml = paginationTpl({
            begin: (self.pageNo-1) * self.pageSize + 1,
            end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
            total: self.total,
            isLastPage: self.isLastPage,
            isFirstPage: self.isFirstPage,
            pageList: pageList

        });
        $('.J_pagination').html(paginationHtml);
        $('.page-item').each((index,item)=>{
            if($(item).data('index')===self.pageNo){
            console.log(this);
            $(item).addClass('active');
        }
    });
    },

    // 绑定事件
    bindEvent: function(){
        let self = PublicBiddingList;
        $('.J_prev').unbind().click(function(){
            if(self.pageNo > 1){
                self.pageNo = self.pageNo -1;
                self.renderList();
            }
        });
        $('.J_next').unbind().click(function(){
            if(self.pageNo < self.maxPage){
                self.pageNo = self.pageNo + 1;
                self.renderList();
            }

        });
        $('.page-item').unbind().click(function(){
            let $item = $(this);

            if(!$item.hasClass('active')){
                self.pageNo = $item.data('index');
                self.renderList();
            }
        });
    },

    // 渲染列表
    renderList(){
        this.getBiddingData()
            .then(this.renderBidList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    }
};

    App.init();
    PublicBiddingList.init();

